package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description WeChatServiceImpl
 * @Author loe
 * @Date 2024-07-11
 */

@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {

    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.secret}")
    private String secret;

    /**
     * 获取OpenId
     * @param code 临时登录凭证 code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> map = getAppConfig();
        map.put("js_code", code);
        String str = HttpUtil.get(GET_OPENID_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(str);
        if (JSONUtil.toJsonStr(jsonObject).contains("errcode")) {
            throw new RuntimeException(BasicEnum.GET_OPENID_ERROR.msg);
        }
        return jsonObject.getStr("openid");
    }

    /**
     * 获取手机号
     * @param code 手机号获取凭证
     * @return
     */
    @Override
    public String getPhone(String code) {
        String access_token = getToken();
        String url = GET_PHONE_URL + access_token;
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        String post = HttpUtil.post(url, JSONUtil.toJsonStr(map));
        JSONObject jsonObject = JSONUtil.parseObj(post);
        if (jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(BasicEnum.GET_PHONE_ERROR.msg);
        } else {
            return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        }
    }

    /**
     * 获取有时效性的token, 为了拿到手机号时使用
     * @return
     */
    public String getToken() {
        Map<String, Object> map = getAppConfig();
        String ret = HttpUtil.get(GET_TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(ret);
        if (jsonObject.getInt("errcode") != null) {
            throw new RuntimeException(BasicEnum.GET_TOKEN_ERROR.msg);
        }
        return jsonObject.getStr("access_token");
    }

    /**
     * 封装公共请求参数
     * @return
     */
    private Map<String, Object> getAppConfig() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("appid", appId);
        requestParam.put("secret", secret);
        return requestParam;
    }
}
